﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NHibernateHelper;
using DOM;
using NHibernate;
using NHibernateHelper;
using NHibernate.Criterion;
using NHibernate.Linq;


namespace BLM
{
    public abstract class BLMFactory<T> where T : class
    {
        /// <summary>
        /// method for saving an object in the database
        /// </summary>
        /// <param name="o"></param>
        public void SaveorUpdate(EntityBase o)
        {
            NHibernateHttpModule.CurrentSession.SaveOrUpdate(o);
        }
        /// <summary>
        /// method for deleting an object from the database
        /// </summary>
        /// <param name="o"></param>
        public void Delete(EntityBase o)
        {
            using (ITransaction tx = NHibernateHttpModule.CurrentSession.BeginTransaction())
            {
                NHibernateHttpModule.CurrentSession.Delete(o);
                tx.Commit();
            }
        }

        /// <summary>
        /// Return iqueryable object from the requested factory
        /// </summary>
        public IQueryable<T> Table
        {
            get { return NHibernateHttpModule.CurrentSession.Query<T>(); }
        }

        /// <summary>
        /// Load object by id method
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T LoadById(int id)
        {
            return NHibernateHttpModule.CurrentSession.CreateCriteria<T>()
                .Add(Expression.Eq("id", id))
                .UniqueResult<T>();
        }

        /// <summary>
        /// Load all objects from database
        /// </summary>
        /// <returns></returns>
        public IList<T> LoadAll()
        {
            return NHibernateHttpModule.CurrentSession.CreateCriteria<T>()
                .List<T>();
        }
    }
}
